package com.sixiaolong.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sixiaolong.common.R;
import com.sixiaolong.domain.Category;
import com.sixiaolong.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 分类管理
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

//    新增分类
    @PostMapping()
    public R saveCategory(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");
    }

//    分页实现
    @GetMapping("page")
    public R<Page> getPage(int page,int pageSize){
        Page<Category> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        categoryService.page(pageInfo,lqw);
        return R.success(pageInfo);
    }
//    根据id删除实现
    @DeleteMapping()
    public R deleteItem(Long id){
        categoryService.remove(id);
        return R.success("删除成功");
//        return R.success("删除成功");
    }

//    修改分类
    @PutMapping()
    public R updateCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }

//    获取条件查询分类数据
    @GetMapping("/list")
    public R<List> getCategory(Category category){
//        log.info("type:"+type);
//        if (String.valueOf(type).equals("")){
//            List<Category> categories = categoryService.list();
//            return R.success(categories);
//        }
//        if (map.get("type").toString() == null){
//            List<Category> categories = categoryService.list();
//            return R.success(categories);
//        }
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(category.getType()!=null,Category::getType,category.getType());
//        对菜品排序  按照sort降序  如果sort值相同则判断修改时间是否相同
        lqw.orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }
}
